package com.cencat.route.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cencat.route.entity.RouteInvoice;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 路线发票信息数据访问层
 * 提供路线发票信息的数据库操作接口
 * 
 * @author cencat
 * @version 1.0
 * @since 2024-01-01
 */
@Mapper
public interface RouteInvoiceMapper extends BaseMapper<RouteInvoice> {

    /**
     * 分页查询路线发票信息
     */
    Page<RouteInvoice> selectRouteInvoicePage(Page<RouteInvoice> page, @Param("invoiceNumber") String invoiceNumber, 
                                             @Param("routeId") Long routeId, @Param("merchantId") Long merchantId,
                                             @Param("invoiceType") String invoiceType, @Param("status") String status);

    /**
     * 条件查询路线发票信息
     */
    List<RouteInvoice> searchRouteInvoices(@Param("conditions") Map<String, Object> conditions);

    /**
     * 根据发票号码查询发票
     */
    @Select("SELECT * FROM route_invoice WHERE invoice_number = #{invoiceNumber} AND deleted = 0")
    RouteInvoice selectByInvoiceNumber(@Param("invoiceNumber") String invoiceNumber);

    /**
     * 根据路线ID查询发票列表
     */
    @Select("SELECT * FROM route_invoice WHERE route_id = #{routeId} AND deleted = 0")
    List<RouteInvoice> selectByRouteId(@Param("routeId") Long routeId);

    /**
     * 根据商户ID查询发票列表
     */
    @Select("SELECT * FROM route_invoice WHERE merchant_id = #{merchantId} AND deleted = 0")
    List<RouteInvoice> selectByMerchantId(@Param("merchantId") Long merchantId);

    /**
     * 根据发票类型查询发票列表
     */
    @Select("SELECT * FROM route_invoice WHERE invoice_type = #{invoiceType} AND deleted = 0")
    List<RouteInvoice> selectByInvoiceType(@Param("invoiceType") String invoiceType);

    /**
     * 根据状态查询发票列表
     */
    @Select("SELECT * FROM route_invoice WHERE status = #{status} AND deleted = 0")
    List<RouteInvoice> selectByStatus(@Param("status") String status);

    /**
     * 根据税务登记号查询发票列表
     */
    @Select("SELECT * FROM route_invoice WHERE tax_number = #{taxNumber} AND deleted = 0")
    List<RouteInvoice> selectByTaxNumber(@Param("taxNumber") String taxNumber);

    /**
     * 批量更新发票状态
     */
    @Update("<script>" +
            "UPDATE route_invoice SET status = #{status}, updated_time = NOW() " +
            "WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateStatus(@Param("ids") List<Long> ids, @Param("status") String status);

    /**
     * 批量更新发票类型
     */
    @Update("<script>" +
            "UPDATE route_invoice SET invoice_type = #{invoiceType}, updated_time = NOW() " +
            "WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateInvoiceType(@Param("ids") List<Long> ids, @Param("invoiceType") String invoiceType);

    /**
     * 批量更新税率
     */
    @Update("<script>" +
            "UPDATE route_invoice SET tax_rate = #{taxRate}, updated_time = NOW() " +
            "WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateTaxRate(@Param("ids") List<Long> ids, @Param("taxRate") BigDecimal taxRate);

    /**
     * 批量更新发票金额
     */
    @Update("<script>" +
            "UPDATE route_invoice SET invoice_amount = #{invoiceAmount}, updated_time = NOW() " +
            "WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateInvoiceAmount(@Param("ids") List<Long> ids, @Param("invoiceAmount") BigDecimal invoiceAmount);

    /**
     * 获取发票统计分析
     */
    Map<String, Object> getInvoiceStatistics(@Param("startTime") LocalDateTime startTime, 
                                            @Param("endTime") LocalDateTime endTime);

    /**
     * 发票税务分析
     */
    Map<String, Object> analyzeTaxData(@Param("merchantId") Long merchantId, 
                                      @Param("startTime") LocalDateTime startTime, 
                                      @Param("endTime") LocalDateTime endTime);

    /**
     * 发票合规性检查
     */
    Map<String, Object> checkInvoiceCompliance(@Param("invoiceId") Long invoiceId);

    /**
     * 查询待开具发票
     */
    @Select("SELECT * FROM route_invoice WHERE status = 'PENDING' AND deleted = 0 ORDER BY created_time ASC")
    List<RouteInvoice> selectPendingInvoices();

    /**
     * 查询已开具发票
     */
    @Select("SELECT * FROM route_invoice WHERE status = 'ISSUED' AND deleted = 0")
    List<RouteInvoice> selectIssuedInvoices();

    /**
     * 查询已作废发票
     */
    @Select("SELECT * FROM route_invoice WHERE status = 'CANCELLED' AND deleted = 0")
    List<RouteInvoice> selectCancelledInvoices();

    /**
     * 查询已红冲发票
     */
    @Select("SELECT * FROM route_invoice WHERE status = 'RED_FLUSHED' AND deleted = 0")
    List<RouteInvoice> selectRedFlushedInvoices();

    /**
     * 查询已审核发票
     */
    @Select("SELECT * FROM route_invoice WHERE status = 'AUDITED' AND deleted = 0")
    List<RouteInvoice> selectAuditedInvoices();

    /**
     * 查询已认证发票
     */
    @Select("SELECT * FROM route_invoice WHERE status = 'VERIFIED' AND deleted = 0")
    List<RouteInvoice> selectVerifiedInvoices();

    /**
     * 检查发票是否存在
     */
    @Select("SELECT COUNT(*) > 0 FROM route_invoice WHERE invoice_number = #{invoiceNumber} AND deleted = 0")
    boolean checkInvoiceExists(@Param("invoiceNumber") String invoiceNumber);

    /**
     * 开具发票
     */
    @Update("UPDATE route_invoice SET status = 'ISSUED', issue_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int issueInvoice(@Param("id") Long id);

    /**
     * 作废发票
     */
    @Update("UPDATE route_invoice SET status = 'CANCELLED', cancel_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int cancelInvoice(@Param("id") Long id);

    /**
     * 红冲发票
     */
    @Update("UPDATE route_invoice SET status = 'RED_FLUSHED', red_flush_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int redFlushInvoice(@Param("id") Long id);

    /**
     * 审核发票
     */
    @Update("UPDATE route_invoice SET status = 'AUDITED', audit_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int auditInvoice(@Param("id") Long id);

    /**
     * 认证发票
     */
    @Update("UPDATE route_invoice SET status = 'VERIFIED', verify_time = NOW(), updated_time = NOW() WHERE id = #{id}")
    int verifyInvoice(@Param("id") Long id);

    /**
     * 更新发票金额
     */
    @Update("UPDATE route_invoice SET invoice_amount = #{amount}, tax_amount = #{taxAmount}, total_amount = #{totalAmount}, updated_time = NOW() WHERE id = #{id}")
    int updateInvoiceAmount(@Param("id") Long id, @Param("amount") BigDecimal amount, 
                           @Param("taxAmount") BigDecimal taxAmount, @Param("totalAmount") BigDecimal totalAmount);

    /**
     * 更新发票税率
     */
    @Update("UPDATE route_invoice SET tax_rate = #{taxRate}, updated_time = NOW() WHERE id = #{id}")
    int updateTaxRate(@Param("id") Long id, @Param("taxRate") BigDecimal taxRate);

    /**
     * 更新发票备注
     */
    @Update("UPDATE route_invoice SET remark = #{remark}, updated_time = NOW() WHERE id = #{id}")
    int updateRemark(@Param("id") Long id, @Param("remark") String remark);

    /**
     * 获取发票收入统计
     */
    Map<String, Object> getInvoiceIncomeStatistics(@Param("merchantId") Long merchantId, 
                                                  @Param("startTime") LocalDateTime startTime, 
                                                  @Param("endTime") LocalDateTime endTime);

    /**
     * 获取税务统计
     */
    Map<String, Object> getTaxStatistics(@Param("merchantId") Long merchantId, 
                                        @Param("startTime") LocalDateTime startTime, 
                                        @Param("endTime") LocalDateTime endTime);

    /**
     * 获取发票类型统计
     */
    Map<String, Object> getInvoiceTypeStatistics(@Param("startTime") LocalDateTime startTime, 
                                                @Param("endTime") LocalDateTime endTime);

    /**
     * 根据时间范围查询发票
     */
    List<RouteInvoice> selectByTimeRange(@Param("startTime") LocalDateTime startTime, 
                                        @Param("endTime") LocalDateTime endTime);

    /**
     * 根据金额范围查询发票
     */
    List<RouteInvoice> selectByAmountRange(@Param("minAmount") BigDecimal minAmount, 
                                          @Param("maxAmount") BigDecimal maxAmount);

    /**
     * 根据税率查询发票
     */
    List<RouteInvoice> selectByTaxRate(@Param("taxRate") BigDecimal taxRate);

    /**
     * 查询增值税专用发票
     */
    @Select("SELECT * FROM route_invoice WHERE invoice_type = 'VAT_SPECIAL' AND deleted = 0")
    List<RouteInvoice> selectVatSpecialInvoices();

    /**
     * 查询增值税普通发票
     */
    @Select("SELECT * FROM route_invoice WHERE invoice_type = 'VAT_ORDINARY' AND deleted = 0")
    List<RouteInvoice> selectVatOrdinaryInvoices();

    /**
     * 查询电子发票
     */
    @Select("SELECT * FROM route_invoice WHERE invoice_type = 'ELECTRONIC' AND deleted = 0")
    List<RouteInvoice> selectElectronicInvoices();

    /**
     * 查询纸质发票
     */
    @Select("SELECT * FROM route_invoice WHERE invoice_type = 'PAPER' AND deleted = 0")
    List<RouteInvoice> selectPaperInvoices();

    /**
     * 查询当月发票
     */
    @Select("SELECT * FROM route_invoice WHERE YEAR(created_time) = YEAR(NOW()) AND MONTH(created_time) = MONTH(NOW()) AND deleted = 0")
    List<RouteInvoice> selectCurrentMonthInvoices();

    /**
     * 查询当年发票
     */
    @Select("SELECT * FROM route_invoice WHERE YEAR(created_time) = YEAR(NOW()) AND deleted = 0")
    List<RouteInvoice> selectCurrentYearInvoices();

    /**
     * 查询超期未开具发票
     */
    @Select("SELECT * FROM route_invoice WHERE status = 'PENDING' AND created_time < DATE_SUB(NOW(), INTERVAL 7 DAY) AND deleted = 0")
    List<RouteInvoice> selectOverdueInvoices();

    /**
     * 查询高金额发票
     */
    @Select("SELECT * FROM route_invoice WHERE total_amount > #{threshold} AND deleted = 0 ORDER BY total_amount DESC")
    List<RouteInvoice> selectHighAmountInvoices(@Param("threshold") BigDecimal threshold);

    /**
     * 发票数据导出
     */
    List<Map<String, Object>> exportInvoiceData(@Param("conditions") Map<String, Object> conditions);

    /**
     * 发票风险评估
     */
    Map<String, Object> assessInvoiceRisk(@Param("invoiceId") Long invoiceId);

    /**
     * 自动计算税额
     */
    BigDecimal autoCalculateTaxAmount(@Param("invoiceAmount") BigDecimal invoiceAmount, 
                                     @Param("taxRate") BigDecimal taxRate);

    /**
     * 发票号码生成
     */
    String generateInvoiceNumber(@Param("merchantId") Long merchantId, 
                                @Param("invoiceType") String invoiceType);

    /**
     * 发票验真
     */
    Map<String, Object> verifyInvoiceAuthenticity(@Param("invoiceNumber") String invoiceNumber, 
                                                 @Param("taxNumber") String taxNumber, 
                                                 @Param("invoiceAmount") BigDecimal invoiceAmount);

    /**
     * 发票重复检查
     */
    boolean checkInvoiceDuplicate(@Param("invoiceNumber") String invoiceNumber, 
                                 @Param("merchantId") Long merchantId, 
                                 @Param("invoiceAmount") BigDecimal invoiceAmount);

    /**
     * 税务申报数据统计
     */
    Map<String, Object> getTaxDeclarationStatistics(@Param("merchantId") Long merchantId, 
                                                   @Param("year") Integer year, 
                                                   @Param("quarter") Integer quarter);

    /**
     * 发票抵扣统计
     */
    Map<String, Object> getInvoiceDeductionStatistics(@Param("merchantId") Long merchantId, 
                                                     @Param("startTime") LocalDateTime startTime, 
                                                     @Param("endTime") LocalDateTime endTime);

    /**
     * 智能发票推荐
     */
    List<Map<String, Object>> intelligentInvoiceRecommendation(@Param("merchantId") Long merchantId, 
                                                              @Param("conditions") Map<String, Object> conditions);

    /**
     * 发票流水号验证
     */
    boolean validateInvoiceSerialNumber(@Param("serialNumber") String serialNumber, 
                                       @Param("invoiceType") String invoiceType);

    /**
     * 发票状态流转记录
     */
    int recordInvoiceStatusChange(@Param("invoiceId") Long invoiceId, 
                                 @Param("fromStatus") String fromStatus, 
                                 @Param("toStatus") String toStatus, 
                                 @Param("operator") String operator, 
                                 @Param("remark") String remark);
}